package com.ruoyi.demo.controller.app;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.demo.domain.AuctionComment;
import com.ruoyi.demo.service.IAuctionCommentService;
import com.ruoyi.demo.utils.RequestUtils;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

/**
 * 小程序-商品评论Controller
 *
 * @author metaee
 * @date 2025-05-06
 */
@Api(tags = "小程序-商品评论")
@RestController
@RequestMapping("/app/comment")
public class AppAuctionCommentController extends BaseController {
    @Autowired
    private IAuctionCommentService auctionCommentService;

    /**
     * 查询商品评论列表
     */
    @ApiOperation("查询商品评论列表")
    @GetMapping("/list")
    public TableDataInfo list(AuctionComment auctionComment) {
        startPage();
        List<AuctionComment> list = auctionCommentService.selectAuctionCommentList(auctionComment);
        return getDataTable(list);
    }

    /**
     * 获取商品评论详细信息
     */
    @ApiOperation("获取商品评论详细信息")
    @GetMapping(value = "/{commentId}")
    public AjaxResult getInfo(@ApiParam(value = "商品评论ID", required = true) @PathVariable("commentId") Long commentId) {
        return success(auctionCommentService.selectAuctionCommentByCommentId(commentId));
    }

    /**
     * 新增商品评论
     */
    @ApiOperation("新增商品评论")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "商品ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "content", value = "评论内容", required = true, dataType = "String")
    })
    @PostMapping
    public AjaxResult add(@RequestBody AuctionComment auctionComment) {
        // 设置当前登录用户ID
        Long userId = RequestUtils.getCurrentUserId();
        if (userId == null) {
            return AjaxResult.error(401, "请先登录");
        }
        auctionComment.setUserId(userId);

        return toAjax(auctionCommentService.insertAuctionComment(auctionComment));
    }

    /**
     * 删除商品评论
     */
    @ApiOperation("删除商品评论")
    @DeleteMapping("/{commentId}")
    public AjaxResult remove(@ApiParam(value = "商品评论ID", required = true) @PathVariable Long commentId) {
        // 验证评论是否属于当前用户
        Long userId = RequestUtils.getCurrentUserId();
        if (userId == null) {
            return AjaxResult.error(401, "请先登录");
        }

        AuctionComment comment = auctionCommentService.selectAuctionCommentByCommentId(commentId);
        if (comment == null) {
            return AjaxResult.error("评论不存在");
        }

        if (!userId.equals(comment.getUserId())) {
            return AjaxResult.error(403, "无权删除他人评论");
        }

        return toAjax(auctionCommentService.deleteAuctionCommentByCommentIds(new Long[]{commentId}));
    }

    /**
     * 根据商品ID查询评论列表
     */
    @ApiOperation("根据商品ID查询评论列表")
    @GetMapping("/goods/{goodsId}")
    public TableDataInfo listByGoodsId(@ApiParam(value = "商品ID", required = true) @PathVariable("goodsId") Long goodsId) {
        startPage();
        AuctionComment auctionComment = new AuctionComment();
        auctionComment.setGoodsId(goodsId);
        auctionComment.setIsHidden("0"); // 只查询未隐藏的评论
        List<AuctionComment> list = auctionCommentService.selectAuctionCommentList(auctionComment);
        return getDataTable(list);
    }

    /**
     * 根据时间排序查询评论列表
     */
    @ApiOperation("根据时间排序查询评论列表")
    @GetMapping("/listByTime")
    public TableDataInfo listByTime(AuctionComment auctionComment,
                                    @ApiParam(value = "排序方式", required = false) @RequestParam(defaultValue = "desc") String orderType) {
        startPage();
        // 设置排序方式，默认按评论时间降序排序（最新的在前面）
        String orderBy = "desc".equalsIgnoreCase(orderType) ? "comment_time desc" : "comment_time asc";
        PageHelper.orderBy(orderBy);

        // 默认只查询未隐藏的评论
        if (auctionComment.getIsHidden() == null) {
            auctionComment.setIsHidden("0");
        }

        List<AuctionComment> list = auctionCommentService.selectAuctionCommentList(auctionComment);
        return getDataTable(list);
    }

    /**
     * 获取用户自己的评论列表
     */
    @ApiOperation("获取用户自己的评论列表")
    @GetMapping("/my")
    public TableDataInfo myComments() {
        Long userId = RequestUtils.getCurrentUserId();
        if (userId == null) {
            return getDataTableForEmptyList();
        }

        startPage();
        AuctionComment auctionComment = new AuctionComment();
        auctionComment.setUserId(userId);
        List<AuctionComment> list = auctionCommentService.selectAuctionCommentList(auctionComment);
        return getDataTable(list);
    }

    /**
     * 隐藏/显示评论（用户只能操作自己的评论）
     */
    @ApiOperation("隐藏/显示评论")
    @PutMapping("/toggleHidden/{commentId}")
    public AjaxResult toggleHidden(@ApiParam(value = "商品评论ID", required = true) @PathVariable Long commentId) {
        // 验证评论是否属于当前用户
        Long userId = RequestUtils.getCurrentUserId();
        if (userId == null) {
            return AjaxResult.error(401, "请先登录");
        }

        AuctionComment comment = auctionCommentService.selectAuctionCommentByCommentId(commentId);
        if (comment == null) {
            return AjaxResult.error("评论不存在");
        }

        if (!userId.equals(comment.getUserId())) {
            return AjaxResult.error(403, "无权操作他人评论");
        }

        // 切换隐藏状态
        AuctionComment updateComment = new AuctionComment();
        updateComment.setCommentId(commentId);
        updateComment.setIsHidden("0".equals(comment.getIsHidden()) ? "1" : "0");

        return toAjax(auctionCommentService.updateAuctionComment(updateComment));
    }

    /**
     * 回复评论
     */
    @ApiOperation("回复评论")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "父评论ID（被回复的评论ID）", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "content", value = "回复内容", required = true, dataType = "String")
    })
    @PostMapping("/reply")
    public AjaxResult reply(@RequestBody AuctionComment auctionComment) {
        // 设置当前登录用户ID
        Long userId = RequestUtils.getCurrentUserId();
        if (userId == null) {
            return AjaxResult.error(401, "请先登录");
        }

        // 验证父评论是否存在
        if (auctionComment.getParentId() == null) {
            return AjaxResult.error("父评论ID（被回复的评论ID）不能为空");
        }

        AuctionComment parentComment = auctionCommentService.selectAuctionCommentByCommentId(auctionComment.getParentId());
        if (parentComment == null) {
            return AjaxResult.error("回复的评论不存在");
        }

        // 设置用户ID和商品ID（商品ID从父评论获取）
        auctionComment.setUserId(userId);
        auctionComment.setGoodsId(parentComment.getGoodsId());

        return toAjax(auctionCommentService.insertAuctionComment(auctionComment));
    }

    /**
     * 获取空数据表格（用于未登录情况）
     */
    private TableDataInfo getDataTableForEmptyList() {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setMsg("操作成功");
        rspData.setRows(Collections.emptyList());
        rspData.setTotal(0);
        return rspData;
    }
}
